package com.itjiange.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 获取数据库连接池对象
 *
 * @author ItJiange
 * @date 2023/10/16
 */
public class DataSourceUtils {
    public static Connection getConnection() {
        // 1. 读取配置文件
        Properties properties = readProperties();
        // 2. 创建线程池并获取连接对象
        DataSource dataSource = getDataSource();
        try (Connection conn = dataSource.getConnection()) {
            return conn;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static DataSource getDataSource() {
        Properties properties = readProperties();
        DataSource dataSource = null;
        try {
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataSource;
    }

    /**
     * 读取配置文件
     * @return
     * @throws IOException
     */
    private static Properties readProperties() {
        Properties properties = new Properties();
        String path = "E:\\1100_study\\1115_KaiFaMiao\\01_ziliao\\06_JavaWeb\\01_object\\java_web\\web-jsp\\src\\main\\resources\\resource.properties";
        try (FileInputStream fileInputStream = new FileInputStream(path)) {
            properties.load(fileInputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return properties;
    }
}
